import React, { Component } from 'react';
import { connect } from 'react-redux'
import _ from 'underscore';
import moment from 'moment';
import ReactDropDown, { ReactDropDownFull } from '../common/dropdown';
import { Tooltip, Input, Upload, Modal, Card, Button, Switch, Icon } from 'antd';

import table from '../charts/table';
import { actions } from '../associator/action/action';
import { orderListTh } from '../associator/static/index';


export class DetailHeader extends Component {
    render() {
        const { headImage, name, details } = this.props;

        return <div className="box-header with-border user-detail-base">
            {headImage ? <img src={`http://47.104.2.156/${headImage}`} className="user-detail-avatar" /> : null}
            <h4>
                <strong>{name}</strong>
            </h4>
            {details.map((i, index) => <p key={index}>
                <span>{i.title} : </span>
                <span>{i.detail}</span>
            </p>)}
        </div>
    }
}

export class DetailEvents extends Component {
    constructor(props) {
        super(props);
        this.state = {
            previewVisible: false,
            previewImage: '',

        }
    }
    handleCancel() {
        this.setState({
            previewVisible: false
        })
    }
    handlePreview(file) {
        this.setState({
            previewImage: file,
            previewVisible: true,
        });
    }

    render() {
        const { eventList, eventTypeMap, isPending, isFinish, loadMore, page, size, contactId, headImage, moreEventMessageType } = this.props;
        const eventGroups = _.groupBy(eventList, function (i) {
            return i.event.eventTimestamp && i.event.eventTimestamp.split(' ')[0]
        });
        const eventGroupKeys = _.keys(eventGroups);
        var params = { page: page + 1, size, contactId };
        const { previewVisible, previewImage } = this.state;
        const handleCancel = this.handleCancel.bind(this);
        const self = this;
        return <div>
            <ul className="timeline timeline-history">
                {eventGroupKeys.map(function (key) {
                    let dailyList = [];

                    eventGroups[key].forEach(function (i, index) {
                        let msgType = i.event.eventType == 1 ? 'visit' : 'shopping';
                        let typoObj = eventTypeMap[msgType];
                        let time = i.event.eventTimestamp;
                        let url = i.store ? `http://47.104.2.156/${i.store.headImage}` : '';
                        let defaultUrl = '/dist/images/default.png';

                        dailyList.push(<li key={index}>
                            <i className={typoObj.icon}></i>
                            <div className="timeline-item">
                                <span className="time">
                                    <Tooltip title={moment(time).format('MMMM Do YYYY, h:mm:ss a')}>
                                        {time}
                                    </Tooltip>
                                </span>
                                <div className="timeline-header no-border clearfix">
                                    {
                                        i.store ? <div onClick={self.handlePreview.bind(self, url)} style={{ display: 'inline-block', verticalAlign: 'middle', width: 50, height: 50, cursor: 'pointer', borderRadius: 4, backgroundImage: `url(${url}), url(${defaultUrl})`, backgroundSize: 'cover', backgroundPosition: 'center' }}></div> : ''
                                    }
                                    <span className="event">{i.deals ? '购买产品' : '门店到访'}</span>
                                    {
                                        i.deals ?
                                            <Card bordered={false}>
                                                <p>订单编号：<a href="javascript: void(0)">{i.deals.billNo}</a></p>
                                                <p>订单金额：<a href="javascript: void(0)">{i.deals.totalAmount}</a></p>
                                                <p>订单数量：<a href="javascript: void(0)">{i.deals.totalQty}</a></p>
                                                <p>订单所属门店：<a href="javascript: void(0)">{i.deals.storeName}</a></p>
                                                {
                                                    i.deals.details.map((item, index) => {
                                                        return <div key={index}>
                                                            <p>商品名：<a href="javascript: void(0)">{item.goodsName}</a></p>
                                                            <p>商品颜色：<a href="javascript: void(0)">{item.colorName}</a></p>
                                                            <p>商品尺寸：<a href="javascript: void(0)">{item.sizeName}</a></p>
                                                        </div>
                                                    })
                                                }
                                            </Card>
                                            :
                                            ''

                                    }

                                </div>
                            </div>
                        </li>)
                    });
                    dailyList.unshift(<li key={key} className="time-label">
                        <span className="user-detail-time-label">{key}</span>
                    </li>);

                    return dailyList
                })}

            </ul>
            {isFinish || isPending ? <div className="user-detail-loadmore text-center">{isFinish ? '没有更多了' : '加载中...'}</div> : <div className="user-detail-loadmore text-center" onClick={() => loadMore(params || {})}>查看更多 <span className="fa fa-angle-double-down"></span></div>}
            <Modal visible={previewVisible} footer={null} onCancel={handleCancel}>
                <img alt="图片显示错误" style={{ width: '100%' }} src={previewImage} />
            </Modal>
        </div>
    }
}

class QrCode extends Component {
    constructor() {
        super();
        this.state = {
            largeQrCode: false
        }
    }
    mouseOver() {
        this.setState({
            largeQrCode: true
        })
    }
    mouseLeave() {
        this.setState({
            largeQrCode: false
        })
    }
    render() {
        const { url } = this.props;
        const largeQrCode = this.state.largeQrCode,
            mouseOver = this.mouseOver.bind(this),
            mouseLeave = this.mouseLeave.bind(this);
        return <div onMouseLeave={mouseLeave} className="qrCodeContainer">
            <img onMouseOver={mouseOver} className="qrCodeImg" src={url} />
            {
                largeQrCode ? <img className="largeQrCodeImg" src={url} /> : ""
            }
        </div>
    }
}

export class DetailPropertyGroup extends Component {
    constructor() {
        super();
        this.state = {
            edit: false
        }
    }
    triggerEdit() {
        this.setState({
            edit: !this.state.edit
        })
    }
    render() {
        const { title, properties, userInfo, editUserInfo, changeVipStatus, saveUserInfo } = this.props;
        const { edit } = this.state;
        return <div className={"box box-solid" + (edit ? ' active' : '')}>
            <div className="box-header with-border">
                <h3 className="box-title" style={{ marginLeft: 5 }}>{title || '属性'}</h3>
                <i className={"fa fa-pencil pull-right" + (edit ? ' active' : '')} onClick={() => this.triggerEdit()}></i>
            </div>
            <div className="box-body no-padding">
                <ul className="nav nav-stacked">
                    {properties.map((i, index) => {
                        return <li key={index}>{(() => {
                            switch (i.type) {
                                case 'select':
                                    return <PropertyWithSelect options={i} list={i.list} />
                                case 'button':
                                    return <PropertyWithButton options={i} edit={edit} changeVipStatus={changeVipStatus} />
                                case 'default':
                                default:
                                    return <PropertyOfDefault options={i} edit={edit} editUserInfo={editUserInfo} />
                            }
                        })()}</li>
                    })}
                </ul>
            </div>
            {edit ? <div className="box-footer">
                <div className="btn btn-danger pull-right" onClick={() => { saveUserInfo(userInfo); this.triggerEdit(); }}>保存更改</div>
                <div className="btn btn-default" onClick={() => this.triggerEdit()}>取消</div>
            </div> : null}
        </div>
    }
}

let orderListOptions = {
    // title: '订单列表',
    limit: 6,
    maxPageCount: 50,
    thead: orderListTh,
    download: true,
    pagebar: true,
    download: false,
    // search: 'vipNo',
    only: true,
    beforeRender: function (data, options) {
        return [
            <DealId data={data} />,
            <ProductName data={data} />,
            <Quantity data={data} />,
            <Amount data={data} />,
            <Time data={data} />
        ]
    },
    trigger: ["trigger"]
}

class DealId extends Component {
    render() {
        const billNo = this.props.data.billNo;
        return <div className="preview-media-limit preview-media-limit-group">
            <p>{billNo}</p>
        </div>
    }
}

class ProductName extends Component {
    render() {
        const goodsName = this.props.data.goodsName;
        return <div className="preview-media-limit preview-media-limit-group">
            <p>{goodsName}</p>
        </div>
    }
}

class Quantity extends Component {
    render() {
        const qty = this.props.data.qty;
        return <div className="preview-media-limit preview-media-limit-group">
            <p>{qty}</p>
        </div>
    }
}

class Amount extends Component {
    render() {
        const amount = this.props.data.amount;
        return <div className="preview-media-limit preview-media-limit-group">
            <p>{amount}</p>
        </div>
    }
}

class Time extends Component {
    render() {
        const billDate = this.props.data.billDate;
        return <div className="preview-media-limit preview-media-limit-group">
            <p>{billDate}</p>
        </div>
    }
}

export class DealTimeline extends Component {
    constructor() {
        super();

        this.state = {
            edit: false
        }
    }
    triggerEdit() {
        this.setState({
            edit: !this.state.edit
        })
    }
    render() {
        const { customerOrder, order, userInfo, linkUserOrder, isLinkOrder, closeLinkOrderPopup, confirmLinkUserOrder, isPending, isFinish, loadMore } = this.props;
        const orderGroups = _.groupBy(customerOrder.data, function (i) {
            return moment(i.billDate).format('YYYY-MM-DD HH:mm:ss');
        });
        const orderGroupKeys = _.keys(orderGroups);
        var params = { page: customerOrder.page + 1, size: customerOrder.size, customerId: userInfo.customerId }
        return <div className={"box box-solid"}>
            <div className="box-header with-border">
                <h3 className="box-title" style={{ marginLeft: 5 }}>客户交易信息</h3>
            </div>
            <div className={"box-body" + (customerOrder && customerOrder.data.length > 0 ? "" : " text-center")}>
                {
                    customerOrder && customerOrder.data.length > 0 ?
                        orderGroupKeys.map((key, index) => {
                            var dataList = [], totalCount = 0;
                            dataList.push(<div className="products-list product-list-in-box">
                                {
                                    orderGroups[key].map((item) => {
                                        var orderDataList = [];
                                        totalCount += item.price;
                                        orderDataList.push(
                                            <li className="item">
                                                <div className="product-img">
                                                    <img src="/dist/images/products.jpg" alt={item.goodsName} />
                                                </div>
                                                <div className="product-info">
                                                    <a href="javascript::;" className="product-title" >
                                                        {item.goodsName}
                                                        <span className="label count pull-right">￥{item.price}</span>
                                                    </a>
                                                    <span className="product-description"> x{item.qty}</span>
                                                </div>
                                            </li>
                                        )
                                        return orderDataList;

                                    })
                                }
                            </div>);
                            dataList.push(
                                <div className="box-footer text-right">
                                    <a href="javascript::;" className="uppercase">总价：￥ {totalCount}</a>
                                </div>
                            );
                            dataList.unshift(<p className="deal-time">{key}</p>);
                            return dataList;
                        })
                        :
                        ''
                }
                {isFinish || isPending ? <div className="user-detail-loadmore text-center">{isFinish ? '没有更多了' : '加载中...'}</div> : <div className="user-detail-loadmore text-center" onClick={() => loadMore(params || {})}>查看更多 <span className="fa fa-angle-double-down"></span></div>}
                {<div style={{ textAlign: 'center', marginTop: '10px' }}><Button type="primary" onClick={linkUserOrder}>关联订单</Button></div>}
            </div>


            {
                // isLinkOrder ?
                //     <div className="link-order">
                //         <div className={"modal fade" + (isLinkOrder ? " in" : '')} style={{ display: 'block' }}>
                //             <div className="modal-dialog">
                //                 <div className="modal-content">
                //                     <div className="modal-header">
                //                         <button type="button" className="close" onClick={closeLinkOrderPopup}>
                //                             <span>&times;</span></button>
                //                         <h4 className="modal-title">关联顾客订单</h4>
                //                     </div>
                //                     <div className="modal-body">
                //                         <DealList options={orderListOptions} />
                //                     </div>
                //                     <div className="modal-footer">
                //                         <button type="button" className="btn btn-default pull-left" onClick={closeLinkOrderPopup}>关闭</button>
                //                         <button type="button" className="btn btn-primary" onClick={() => confirmLinkUserOrder(order, userInfo)}>确认关联</button>
                //                     </div>
                //                 </div>
                //             </div>
                //         </div>
                //     </div>
                //     :
                //     ''
            }
            <Modal visible={isLinkOrder} title="关联顾客订单" onCancel={closeLinkOrderPopup} footer={[
                <Button key="back" size="large" onClick={closeLinkOrderPopup}>取消</Button>,
                <Button key="submit" disabled={!order.checked.length} type="primary" size="large" onClick={() => confirmLinkUserOrder(order, userInfo)}>
                    确认
                </Button>,
            ]} >
                <DealList options={orderListOptions} />
            </Modal>

        </div>
    }
}



const DealList = connect(
    function (state) {
        return state.userDetail.order
    },
    function (dispatch) {
        return {
            getData: (params) => {
                actions.orderListSetPageIndex(dispatch, params);
                actions.orderListRenderData(dispatch, params);
                actions.orderListRequest(dispatch, params);
            },
            onCheck: (params) => {
                dispatch({
                    type: 'order-list-set-checked',
                    val: params
                });
            }
        }
    }
)(table);

class PropertyOfDefault extends Component {
    render() {
        const { options, edit, editUserInfo } = this.props;
        const { name, content } = options;
        return <a>
            <div className="row">
                <span className="col-md-4">{name}</span>
                {
                    edit ?
                        name == '创建时间' ?
                            <span className="col-md-8 text-right">{content.length > 0 ? content : '--'}</span>
                            :
                            <input name={name} onChange={editUserInfo} type="text" className="col-md-8 text-right edit" value={content} />
                        :
                        <span className="col-md-8 text-right">{content.length > 0 ? content : '--'}</span>
                }
            </div>
        </a>
    }
}

class PropertyWithButton extends Component {

    render() {
        const { options, edit, changeVipStatus } = this.props;
        const { name, content } = options;
        return (
            <a>
                <div className="row">
                    <span className="col-md-4">{name}</span>
                    <Switch disabled={!edit} onChange={changeVipStatus} checkedChildren="是" unCheckedChildren="否" defaultChecked={content == '1' ? true : false} />

                </div>
            </a>
        );
    }
}

class PropertyWithSelect extends Component {
    render() {
        const { options, list } = this.props;
        const { name, val, callback } = options;

        return <a>
            <div className="row">
                <span className="col-md-4">{name}</span>
                <span className="col-md-8 text-right">
                    <select className="form-control input-sm" value={val} onChange={(e) => callback(e.target.value)}>
                        {list.map((i, index) => <option key={i.value} value={i.value}>{i.name}</option>)}
                    </select>
                </span>
            </div>
        </a>
    }
}